package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;

import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.*;


@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Value("${sky.baidu.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;


    @Autowired
    AddressBookMapper addressBookMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    WeChatPayUtil weChatPayUtil;

    @Autowired
    OrderService orderService;

    @Autowired
    DishMapper dishMapper;

    @Autowired
    SetmealMapper setmealMapper;

    @Autowired
    WebSocketServer webSocketServer;



    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO submitDTO) {


        //用户的查询地址
        AddressBook addressBook = addressBookMapper.getById(submitDTO.getAddressBookId());
        if(addressBook==null){
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());

        User user = userMapper.getUserById(BaseContext.getCurrentId());
        if(user==null){
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }

        //查询购物车
        List<ShoppingCart> shoppingCart = shoppingCartMapper.getShoppingCart(BaseContext.getCurrentId());
        if(shoppingCart==null){
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //1、订单数据存入订单表
        Orders orders=new Orders();
        //capy拷贝属性
        BeanUtils.copyProperties(submitDTO,orders);
        orders.setNumber(UUID.randomUUID().toString());//设置订单编号
        orders.setStatus(Orders.PENDING_PAYMENT );
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);

        orders.setPhone(addressBook.getPhone());//电话

        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserName(user.getName());//下单人姓名

       orderMapper.insert(orders);
       log.info("id信息："+orders.getId());


        //2、订单明细表存入订单明细表
        List<OrderDetail> orderDetailList=new ArrayList<>();
        shoppingCart.forEach(cart -> {
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail,"id");
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });

        log.info("订单详表："+orderDetailList);
        orderMapper.insertBatch(orderDetailList);


        //3、清空购物车
        shoppingCartMapper.clean(user.getId());


        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }



    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        //User user = userMapper.getById(userId);
//        User user = userMapper.getUserById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;

        //业务处理，修改订单状态、来单提醒
        orderService.paySuccess(ordersPaymentDTO.getOrderNumber());



        //模拟支付成功！
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

//        //使用websocket向客户端推送订单消息,来单提醒
//        Map map=new HashMap();
//        map.put("type",1);
//        map.put("orderId", ordersDB.getId());
//        map.put("content","订单号:"+ordersDB.getNumber());
//        String json = JSON.toJSONString(map);
//        webSocketServer.sendToAllClient(json);
        //////////////////////////////////////////////
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        ///////////////////////////////////////////////////


    }


    //===================================day09实战


    @Override
    public PageResult getOrder(OrdersPageQueryDTO dto) {

        //设置分页参数
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        //查询订单
        List<OrderVO> orderList = orderMapper.getOrderList(dto);


        for (OrderVO orderVO : orderList) {
            //根据订单信息查询出订单中的彩品或者套餐
            List<OrderDetail> orderDetails = orderMapper.getOrderDetailById(Math.toIntExact(orderVO.getId()));
            //将订单详情数据给ordreVO
            orderVO.setOrderDetailList(orderDetails);
            //订单所有订单和套餐的名字
            String orderDishes="";
            //获取订单详情中的套餐id
            for (OrderDetail orderDetail : orderDetails) {
                //订单id
                Long did = orderDetail.getDishId();

                //套餐id
                Long sid = orderDetail.getSetmealId();

                if(did!=null){
                    DishVO dish = dishMapper.getDish(did);
                    orderDishes+=dish.getName()+"*"+orderDetail.getNumber()+";";

                }
                if(sid!=null){
                    SetmealVO setmeal = setmealMapper.getSetmealById(sid);
                    orderDishes+=setmeal.getName()+"*"+orderDetail.getNumber()+";";
                }

            }


            orderVO.setOrderDishes(orderDishes);
        }



        Page page= (Page) orderList;
        return new PageResult(page.getTotal(),page.getResult());
    }


    /**
     * 修改订单
     * @param dto
     */
    @Override
    public void updateStatus(OrdersConfirmDTO dto) {
        dto.setStatus(Orders.CONFIRMED);
        orderMapper.updateStatus(dto);
    }


    @Override
    public OrderVO getOrderDetailById(Integer id) {
        //构造要返回的参数
        OrderVO orderVO =new OrderVO();

        //查询订单
        Orders order = orderMapper.getOrderById(id);
        log.info("查询到的订单信息："+order);

        //将order的数据copy到orderVO中
        BeanUtils.copyProperties(order,orderVO);
        //根据订单信息查询出订单中的彩品或者套餐
        List<OrderDetail> orderDetails = orderMapper.getOrderDetailById(id);
        //将订单详情数据给ordreVO
        orderVO.setOrderDetailList(orderDetails);
        //订单所有订单和套餐的名字
        String orderDishes="";
        //获取订单详情中的套餐id
        for (OrderDetail orderDetail : orderDetails) {
            //订单id
            Long did = orderDetail.getDishId();

            //套餐id
            Long sid = orderDetail.getSetmealId();

            if(did!=null){
                DishVO dish = dishMapper.getDish(did);
                orderDishes+=dish.getName()+"*"+orderDetail.getNumber()+";";

            }
            if(sid!=null){
                SetmealVO setmeal = setmealMapper.getSetmealById(sid);
                orderDishes+=setmeal.getName()+"*"+orderDetail.getNumber()+";";
            }

        }


        orderVO.setOrderDishes(orderDishes);


        //获取订单有的菜品名
//        List<Dish> dishNameList = dishMapper.getDishByIdList(dishId);
//
//        dishNameList.forEach(dishName -> {
//            dishName
//        });


        log.info("返回前的vo："+orderVO);
        return orderVO;
    }

    @Override
    public void updateDispatchOrdersStatus(Long id) {
        OrdersConfirmDTO dto =new OrdersConfirmDTO();
        dto.setStatus(Orders.DELIVERY_IN_PROGRESS);
        dto.setId(id);
        orderMapper.updateStatus(dto);
    }

    @Override
    public void updateCompleteOrdersStatus(Long id) {
        OrdersConfirmDTO dto =new OrdersConfirmDTO();
        dto.setStatus(Orders.COMPLETED);
        dto.setId(id);
        orderMapper.updateStatus(dto);
    }

    @Override
    public void updateCancelOrdersStatus(OrdersCancelDTO dto)  {
        //非已完成状态都可取消
        Orders order = orderMapper.getStatusOfOrder(dto.getId());
        log.info("状态码："+order.getStatus());

        if(order.getStatus()==Orders.COMPLETED){
            throw new OrderBusinessException(MessageConstant.ORDERS_COMPLATE);
        }

        /**
         * 模拟退款成功
         */

//        //退款操作（有个异常需要处理！！）
//        String refund = weChatPayUtil.refund(order.getNumber(), order.getNumber(), order.getAmount(), order.getAmount());
//        //解析返回结果判断是否退款成功
//        JSONObject jsonObject= JSON.parseObject(refund);
//        String status = jsonObject.getString("status");
//        if(!"success".equals(status)){
//            throw  new OrderBusinessException("退款失败！");
//        }


        //直接修改状态为 6（已取消）
        orderMapper.updateCancelOrdersStatus(dto);
    }

    @Override
    public void updateRejectionOrder(OrdersRejectionDTO dto) {

        /**
         * 模拟退款成功
         */

//        //退款操作
//        String refund = weChatPayUtil.refund(order.getNumber(), order.getNumber(), order.getAmount(), order.getAmount());
//        //解析返回结果判断是否退款成功
//        JSONObject jsonObject= JSON.parseObject(refund);
//        String status = jsonObject.getString("status");
//        if(!"success".equals(status)){
//            throw  new OrderBusinessException("退款失败！");
//        }

        //直接修改状态为 6（已取消）
        orderMapper.updateRejectionOrder(dto);

    }


    @Override
    public OrderStatisticsVO statisticsOrders() {
        //构造单数统计对象
        OrderStatisticsVO statisticsVO=new OrderStatisticsVO(0,0,0);

        //统计数据
        //待派送订单数量
        Integer confirmed = orderMapper.getStatusNum(Orders.CONFIRMED);//已接单的待派送
        if(confirmed!=null){
            statisticsVO.setConfirmed(confirmed);
        }


        //派送订单数量
        Integer deliveryInProgress = orderMapper.getStatusNum(Orders.DELIVERY_IN_PROGRESS);//派送中
        if(deliveryInProgress!=null){
            statisticsVO.setDeliveryInProgress(deliveryInProgress);
        }

        //待接单数量
        Integer toBeConfirmed = orderMapper.getStatusNum(Orders.TO_BE_CONFIRMED);//已接单的待派送
        if(toBeConfirmed!=null){
            statisticsVO.setToBeConfirmed(toBeConfirmed);
        }

        return statisticsVO;
    }


    /**
     * 查询历史订单
     * @param page
     * @param pageSize
     * @param status
     */
    @Override
    public PageResult getHistoryOrders(Integer page, Integer pageSize, Integer status) {
        //分页参数
        PageHelper.startPage(page,pageSize);

        //查询当前用户的而订单
        List<OrderVO> ordersList = orderMapper.getBysTatusAndUserId(status, BaseContext.getCurrentId());//可使用resultMap数据映射一条sql查

        Page p= (Page) ordersList;

        if(ordersList.size()>0 && ordersList !=null){
            for (OrderVO orderVO : ordersList) {
                //获取每个订单的id
                Integer id = Math.toIntExact(orderVO.getId());
                log.info("每个订单id："+id );

                //根据订单id获取订单中的所有的残品
                List<OrderDetail> orderDetailList = orderMapper.getOrderDetailById(id);
                orderVO.setOrderDetailList(orderDetailList);

            }
        }

        //Page p= (Page) ordersList;
        return new PageResult(p.getTotal(),ordersList);
    }


    /**
     * 用户端取消订单
     * @param id
     */
    @Override
    public void CancelOrdersStatus(Integer id) {
        Orders order = orderMapper.getOrderById(id);
        //        //退款操作
//        String refund = weChatPayUtil.refund(order.getNumber(), order.getNumber(), order.getAmount(), order.getAmount());
//        //解析返回结果判断是否退款成功
//        JSONObject jsonObject= JSON.parseObject(refund);
//        String status = jsonObject.getString("status");
//        if(!"success".equals(status)){
//            throw  new OrderBusinessException("退款失败！");
//        }

        //将订单改为取消状态
        OrdersCancelDTO dto =new OrdersCancelDTO();
        dto.setId(order.getId());
        dto.setCancelReason("用户取消");
        orderMapper.updateCancelOrdersStatus(dto);


    }


    @Override
    public void reOrder(Integer id) {
        //根据原来订单id 查出原来订单的相关菜品或者套餐
        List<OrderDetail> orderDetailList = orderMapper.getOrderDetailById(id);

        //构造参数，购物车添加
        ShoppingCartDTO dto =new ShoppingCartDTO();

        for (OrderDetail orderDetail : orderDetailList) {
            dto.setDishId(orderDetail.getDishId());//菜品id

            if(orderDetail.getSetmealId()!=null){
                dto.setSetmealId(orderDetail.getSetmealId());
            }

            if(orderDetail.getDishFlavor()!=null){
                dto.setDishFlavor(orderDetail.getDishFlavor());
            }

            //可复用购物车的业务方add法
            //属性copy
            ShoppingCart cart=new ShoppingCart();
            BeanUtils.copyProperties(dto,cart);
            cart.setUserId(BaseContext.getCurrentId());//设置用户id

            //查询是否有对应的套餐或者菜品订单在购物车
            ShoppingCart shoppingCart = shoppingCartMapper.selectBy(cart);
            if(shoppingCart==null){//购物车没有该菜品或者套餐

                if(cart.getDishId()!=null){//不为空说明购物车里的是菜品不是套餐
                    //查询对应要添加的菜品信息
                    DishVO dish = dishMapper.getDish(cart.getDishId());
                    cart.setName(dish.getName());
                    cart.setAmount(dish.getPrice());
                    cart.setImage(dish.getImage());

                }else {//否则购物车里的是套餐
                    SetmealVO setmealById = setmealMapper.getSetmealById(cart.getSetmealId());
                    cart.setName(setmealById.getName());
                    cart.setAmount(setmealById.getPrice());
                    cart.setImage(setmealById.getImage());

                }
                cart.setNumber(1);
                cart.setCreateTime(LocalDateTime.now());
                shoppingCartMapper.insert(cart);

            }else{//购物车有
                shoppingCart.setNumber(shoppingCart.getNumber()+1);
                shoppingCartMapper.update(shoppingCart);
            }

        }


    }



    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        log.info("距离："+distance+"米");
        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("不要意思您不在配送范围");
        }
    }

    @Override
    public void reMinderById(Integer id) {

        //查询订单信息
        Orders order = orderMapper.getOrderById(id);

        if(order.getStatus()<4 && order !=null){
            Map map=new HashMap<>();
            map.put("type",2);//2 表示催单
            map.put("orderId",order.getId());
            map.put("content","订单号："+order.getNumber());
            String jsonString = JSON.toJSONString(map);

            //使用websocket 向客户端发送催单
            webSocketServer.sendToAllClient(jsonString);

        }


    }


    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);
        log.info(dateList.toString());

        String dateString ="";

        //将营业封装到里面
        List<Double> turnover=new ArrayList();
        //遍历日期差选每天的营业额
        for (LocalDate date : dateList) {

            //日期抽取方法
            dateString += getDateString(date);

            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime  beginTime= LocalDateTime.of(date, LocalTime.MIN);

            log.info("开始时间：{}",beginTime);
            log.info("结束时间：{}",endTime);
            //查询已经当天完成的订单的营业额
            Double turnoverByDay = orderMapper.getTurnoverByDay(beginTime, endTime, Orders.COMPLETED);
            turnoverByDay = turnoverByDay == null ? 0.0 : turnoverByDay;
            turnover.add(turnoverByDay);
        }



        //String join = StringUtil.join(",", dateList);

        //将营业额转换成字符串
       String turnoverList = StringUtils.join(turnover,',');
//        String listDate = StringUtils.join(dateList,',');
        log.info("时间列表"+dateString);
        log.info("营业额："+turnoverList);

//        log.info("时间列表"+listDate.substring(0, listDate.length()-1));
//        log.info("营业额："+turnoverList.substring(1,turnoverList.length()-1));
        //return new TurnoverReportVO(listDate,turnoverList);

      return new TurnoverReportVO(dateString.substring(0, dateString.length()-1),turnoverList);
    }

    /**
     * 用户注册数量统计
     * @param begin
     * @param end
     * @return
     */

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);



        //用户总量
        List totalUserList=new ArrayList<>();

        //新增用户
        List newUserList=new ArrayList<>();

        //日期字符串
        String dateString="";
        for (LocalDate date : dateList) {
             dateString += getDateString(date);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime  beginTime= LocalDateTime.of(date, LocalTime.MIN);
            log.info("开始时间：{}",beginTime.getClass().getName());
            log.info("结束时间：{}",endTime.getClass().getName());


             //获取当天的新用户数量
            Integer newUserNum = userMapper.getUserByTime(beginTime, endTime);
            newUserNum = newUserNum == null ? 0 : newUserNum;
            newUserList.add(newUserNum);


            //获取当天之前的用户总量
            Integer userTotal = userMapper.getUserByTime(null,endTime);
            totalUserList.add(userTotal);

        }

        String newUser = StringUtils.join(newUserList, ",");
        String totalUseer = StringUtils.join(totalUserList, ",");


        return new UserReportVO(dateString,totalUseer,newUser);
    }



    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);

        //订单总数
        Integer totalOrderCount=0;
        //每日订单数
        List orderCountList=new ArrayList();


        //有效订单总数
        Integer validOrderCount=0;
        //每日有效订单数
        List validOrderCountList= new ArrayList();





        //日期字符串
        String dateString="";
        for (LocalDate date : dateList) {
            dateString += getDateString(date);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);


            //获取每日订单数 每天的所有订单
            Integer orderTotalByDay = orderMapper.getOrderByTime(beginTime, endTime, null);
            orderCountList.add(orderTotalByDay);

            //累加到订单总数
            totalOrderCount+=orderTotalByDay;


            //每天的有效订单数
            Integer validOrderCountDay = orderMapper.getOrderByTime(beginTime, endTime,Orders.COMPLETED);
            validOrderCountList.add(validOrderCountDay);

            validOrderCount+=validOrderCountDay;


        }

        //订单完成率
        Double orderCompletionRate= (double) 0;
        if(validOrderCount!=0&& totalOrderCount !=0){
             orderCompletionRate= ((double) validOrderCount)/totalOrderCount;
        }

        //  每日订单数 orderCountList
        String orderCountListByDay = StringUtils.join(orderCountList, ",");

        //每日有效订单数
        String validOrderCountListByDay = StringUtils.join(validOrderCountList, ",");


        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(dateString.substring(0,dateString.length()-1));
        orderReportVO.setOrderCountList(orderCountListByDay);
        orderReportVO.setValidOrderCountList(validOrderCountListByDay);
        orderReportVO.setTotalOrderCount(totalOrderCount);
        orderReportVO.setValidOrderCount(validOrderCount);
        orderReportVO.setOrderCompletionRate(orderCompletionRate);

        return orderReportVO;
    }


    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //计算时间范围
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);


        //统计菜品和套餐的数量
        List<Map> top10List = orderMapper.getTop10ByTime(beginTime, endTime);
        log.info("排行榜："+top10List);

        //排行榜菜品套餐名
        List nameList=new ArrayList();
        //排行榜数量
        List numberList=new ArrayList();

        for (Map map : top10List) {
            log.info("map"+map);
            Object num = map.get("num");
            log.info("num:"+num);
            Object name = map.get("name");
            log.info("name:"+name);
            nameList.add(name);
            numberList.add(num);

        }

        String name = StringUtils.join(nameList, ",");
        String number = StringUtils.join(numberList, ",");


        return new SalesTop10ReportVO(name,number);
    }

    private static String getDateString(LocalDate date) {
        String listDate="";
        //日期只显示月份和日期 例：5-14
        int month = date.getMonthValue();
        int day = date.getDayOfMonth();
        listDate +=month+"-"+day+",";
        return listDate;
    }





    /**
     * 日期列表
     * @param begin
     * @param end
     * @return
     */
    private static List<LocalDate> getLocalDates(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);//日期计算，获得指定日期后1天的日期
            dateList.add(begin);
        }

        return dateList;
    }



}
